
import { authorizedUser } from "./base"
export const getWxToken = () => {
	try {
		const value = uni.getStorageSync('WX_TOKEN');
		return value;
	} catch (e) {
		// error
		return ""
	}
}

// 返回参数状态处理

export const errorStatus = {
	USER_CANT_FIND: "无当前用户",
	USER_STATE_0: "用户被禁用",
	USER_DEL_1: "用户被删除",
	CARD_NUMBER_PASSWORD_MISMATCH: "卡号卡密不匹配",
	EQUITY_CARD_CONFIG_INVALID: "权益卡配置无效",
	EQUITY_CARD_CONFIG_STATE_0: "权益卡配置未发布",
	EQUITY_CARD_CONFIG_DEL_1: "权益卡配置已删除",
	CARD_HAS_ACTIVE: "权益卡已激活",
	CARD_HAS_DEL: "权益卡已删除",
	ACTIVATION_EXPIRED: "超过激活期限",
	ACTIVE_SUCCESS: "激活成功",
	PARAMS_ERROR: "参数缺失",
	CUSTOMER_UNDEFINE: '无微信绑定的用户',
	CUSTOMER_STATE_0: '用户状态异常',
	CUSTOMER_DEL_1: '用户已经被删除',
	CARD_UNDEFINE: '无指定的权益卡',
	CARD_ACTIVE_STATE_0: '权益卡未激活',
	CARD_DEL_1: '权益卡已被删除',
	CARD_CUSTOMER_NOT_MATCH: '权益卡绑定用户和当前用户不匹配',
	CARD_VALID_PERIOD_OVER: '权益卡有效期失效',
	CARD_HAS_NO_EQUITY_TYPE: '权益卡没有这个类型的权益',
	CARD_EQUITY_IS_IN_WAIT: '当前权益还在等待期中',
	APPLY_SUCCESS: '提单成功',
	WX_USER_NOT_LOGIN: '微信用户未登录',
	PARAMS_ERROR: '参数缺失',
	ORDER_DUPLICATE: '重复的预约订单',
	CARD_CONFIG_NOT_CAN_USE: '剩余使用次数已用完',
	CARD_ENABLE_0: "权益卡未启用",
	UNKNOW: '未知',
}

// 授权登录
export const loginAuthorize = () => {
	return new Promise((resolve, reject) => {
		uni.login({
			provider: 'weixin',
			success: function (loginRes) {
				// 登录成功
				uni.getUserInfo({
					desc: '用于完善会员资料',
					lang: "zh_CN",
					success: function (info) {
						// 获取用户信息成功, info.authResult保存用户信息
						// resolve({ ...info, ...loginRes });
						let resInfo = { ...info, ...loginRes }
						let params = {
						  code: resInfo.code,
						  userInfo: {
						    iv: resInfo.iv,
						    encryptedData: resInfo.encryptedData,
						    signature: resInfo.signature,
						  },
						};
						authorizedUser(params).then((res) => {
						  console.log(res, "res");
						  if (res.data.code === 200) {
						    uni.setStorageSync("WX_TOKEN", res.data.data.wxToken);
							resolve(res.data.data);
						  }
						});
					},
					fail: (err) => {
						console.error('用户拒绝授权:', err);
						reject(err);
						uni.showToast({ title: '授权失败', icon: 'none' });
					}
				})
			},
			fail: function (err) {
				// 登录授权失败
				// err.code是错误码
			}
		});
	})
	
}


// 日期格式化

export function parseTime(time, pattern) {
	if (arguments.length === 0 || !time) {
		return null
	}
	const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
	let date
	if (typeof time === 'object') {
		date = time
	} else {
		if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
			time = parseInt(time)
		} else if (typeof time === 'string') {
			time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
		}
		if ((typeof time === 'number') && (time.toString().length === 10)) {
			time = time * 1000
		}
		date = new Date(time)
	}
	const formatObj = {
		y: date.getFullYear(),
		m: date.getMonth() + 1,
		d: date.getDate(),
		h: date.getHours(),
		i: date.getMinutes(),
		s: date.getSeconds(),
		a: date.getDay()
	}
	const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
		let value = formatObj[key]
		// Note: getDay() returns 0 on Sunday
		if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
		if (result.length > 0 && value < 10) {
			value = '0' + value
		}
		return value || 0
	})
	return time_str
}


/**
* 校验中国手机号码
* @param {string} phone 手机号码
* @returns {boolean} 是否合法
*/
export function validatePhone(phone) {
 const reg = /^1[3-9]\d{9}$/;
 return reg.test(phone);
}

/**
* 校验中国身份证号码（基础格式校验）
* @param {string} idCard 身份证号码
* @returns {boolean} 是否合法
*/
export function validateIDCard(idCard) {
 const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[\dXx]$/i;
 return reg.test(idCard);
}

export function handleBlob(blob, mimeType) {
	// 创建临时 URL
	const url = URL.createObjectURL(new Blob([blob], { type: mimeType }));
	return url;
  }

  // 将ArrayBuffer转换为Base64编码
  export function  arrayBufferToBase64(buffer) {
	// 将ArrayBuffer转换为Uint8Array
	const bytes = new Uint8Array(buffer);
	// 初始化一个空字符串
	let binary = '';
	// 遍历Uint8Array中的每个字节
	for (let i = 0; i < bytes.byteLength; i++) {
	  // 将每个字节转换为字符，并拼接到binary字符串中
	  binary += String.fromCharCode(bytes[i]);
	}
	// 将binary字符串转换为Base64编码并返回
	return btoa(binary);
  };
  // 导出一个函数，用于将base64格式的图片保存到小程序的临时文件中
  export function  saveBase64ToTempFileMiniProgram(base64, mimeType) {
	// 返回一个Promise对象
	return new Promise((resolve, reject) => {
	  // 根据mimeType获取文件扩展名，默认为png
	  const ext = mimeType.split('/')[1] || 'png';
	  // 构造文件路径，使用当前时间戳作为文件名
	  const filePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.${ext}`;
	  // 获取文件系统管理器
	  const fs = wx.getFileSystemManager();
	  // 写入文件
	  fs.writeFile({
		filePath,
		data: base64,
		encoding: 'base64',
		success: () => resolve(filePath),
		fail: reject
	  });
	});
  };